package cn.tmpan.project.controller.system;

import cn.tmpan.project.common.ServerResponse;
import cn.tmpan.project.common.enums.ResponseCode;
import cn.tmpan.project.model.vo.SystemStatusVo;
import cn.tmpan.project.utils.QRCodeUtil;
import io.swagger.annotations.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * The type Sys tem controller.
 *
 * @Author tieMinPan
 * @Desc: Description
 * @Date 2019 -05-24 14:07
 */
@Controller
@Api(tags = "系统全局性接口")
@RequestMapping(value = "other")
public class SysTemController {


    /**
     * 测试接口
     *
     * @param userName the user name
     * @param password the password
     * @return server response
     */
    @ApiImplicitParams({
            @ApiImplicitParam(value = "户主姓名", name = "hzxm", required = true),
            @ApiImplicitParam(value = "密码", name = "password")
    })
    @ApiOperation(value = "测试接口文档接口", response = ServerResponse.class)
    @GetMapping(value = "swagger")
    @ResponseBody
    public ServerResponse test(String userName, String password) {
        return ServerResponse.createBySuccessMessage("测试通过:" + userName + " " + password);
    }


    /**
     * 下载指定文件
     *
     * @param request
     * @param response
     * @param fileName
     * @param dir
     * @return
     * @throws UnsupportedEncodingException
     */
    @ApiOperation(value = "下载指定文件")
    @GetMapping(value = "downloadFile")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "文件全名", name = "fileName", required = true, example = "测试文件.zip"),
            @ApiImplicitParam(value = "webApps下文件夹路径/", name = "dir", required = true, example = "excel")
    })
    @ResponseBody
    public ServerResponse downloadFile(HttpServletRequest request, HttpServletResponse response, String fileName, String dir) throws IOException {
        request.setCharacterEncoding("UTF-8");
        String path = request.getSession().getServletContext().getRealPath(dir);
        response.setCharacterEncoding("UTF-8");
        if (fileName != null) {
            // 修复文件下载高危BUG linux
            fileName = fileName.replace("../", "_");
            // win
            fileName = fileName.replace("..", "_");
            fileName = fileName.trim();
            File file = new File(path, "/" + fileName);
            if (file.exists()) {
                /**
                 *@desc 设置强制下载不打开
                 */
                response.setContentType("application/octet-stream;charset=UTF-8");
                /**
                 *@desc 设置文件名
                 */
                response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("UTF-8"), "iso-8859-1"));

                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    response.setHeader("Content-Length", String.valueOf(fis.getChannel().size()));
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        bis.close();
                    }
                    if (fis != null) {
                        fis.close();
                    }
                }
            }
        }
        return ServerResponse.createByErrorMessage("文件不存在,请先生成文件后重试!");
    }

    /**
     * 显示多维码
     *
     * @param str
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "显示指定图片")
    @GetMapping(value = "displayImages")
    @ApiParam(value = "条形码内容", name = "str", example = "1234567890", required = true)
    public void displayImages(String str, HttpServletResponse response) throws IOException {
        BufferedImage bufferedImage = QRCodeUtil.generateBarcodeAndText(str);
        //将图片输出给浏览器
        response.setContentType("image/png");
        OutputStream os = response.getOutputStream();
        ImageIO.write(bufferedImage, "png", os);
    }



    /**
     * 获取系统状态码
     * @return
     */
    @ApiOperation(value = "获取系统状态码")
    @GetMapping(value = "getSystemStatusCode")
    @ResponseBody
    public ServerResponse getSystemStatusCode() {
        List<SystemStatusVo> systemStatusVoList = new ArrayList<SystemStatusVo>(10);
        for (ResponseCode e : ResponseCode.values()) {
            SystemStatusVo systemStatusVo = new SystemStatusVo(e.getCode(), e.getDesc());
            systemStatusVoList.add(systemStatusVo);
        }
        return ServerResponse.createBySuccess(systemStatusVoList);
    }

}
